package com.spring.activity;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;
import com.spring.framgent.Fav_Fragment;
import com.spring.framgent.Index_Fragment;

import com.spring.framgent.Setting_Fragment;

import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.QueryVersion;
import com.spring.service.NotificationService;

import com.spring.tool.App;
import com.spring.util.Constant;
import com.spring.util.DummyTabContent;
import com.spring.util.StatusBar;
import com.spring.util.SystemBarTintManager;
import com.tencent.android.tpush.XGCustomPushNotificationBuilder;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.common.Constants;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.lang.ref.WeakReference;

/**
 * @version V1.0
 * @Description: 主Activity，底部TabHost选项卡
 * @Author Hades
 * @date 2012-10-6
 */

public class MainActivity extends FragmentActivity implements
        OnPageChangeListener {
    private int currentV = 0, newV = 0;
    private JSONObject jo_v;
    private String newVContent = "";
    String Content;
    private ProgressBar pb;
    private TextView tv;
    public static int loading_process;
    TabHost tabHost;
    TabWidget tabWidget;
    LinearLayout bottom_layout;
    int CURRENT_TAB = 5; // 设置常量
    Fav_Fragment homeFragment;


    Setting_Fragment meFragment;
    Index_Fragment index_Fragment;
    android.support.v4.app.FragmentTransaction ft;
    LinearLayout tabIndicator1, tabIndicator2, tabIndicator3, tabIndicator4,
            tabIndicator5;
    private Button btnlooad;
    QueryVersion contactData;
    Dialog dialog;
    String filename;
    RestClient restClient = null;
    private NotificationService notificationService;// 获取通知数据服务
    private int allRecorders = 0;// 全部记录数
    private int pageSize = 1;// 默认共1页
    private boolean isLast = false;// 是否最后一条
    private int firstItem;// 第一条显示出来的数据的游标
    private int lastItem;// 最后显示出来数据的游标
    private String id = "";// 查询条件
    private boolean isUpdate = false;
    private Fav_Fragment.MsgReceiver updateListViewReceiver;
    Message m = null;
    private Context context;
    Bundle data;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XGPushConfig.enableDebug(this, true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            new StatusBar(true, this);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.deep_bule);//通知栏所需颜色
        }
        setContentView(R.layout.activity_main);
         data = new Bundle();
        findTabView();
        // 0.注册数据更新监听器
        updateListViewReceiver = new Fav_Fragment.MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qq.xgdemo.activity.UPDATE_LISTVIEW");
        registerReceiver(updateListViewReceiver, intentFilter);
        // 1.获取设备Token
        Handler handler = new HandlerExtension(MainActivity.this);
        m = handler.obtainMessage();
        // 注册接口
        XGPushManager.registerPush(getApplicationContext(),
                new XGIOperateCallback() {
                    @Override
                    public void onSuccess(Object data, int flag) {
                        Log.i(Constants.LogTag,
                                "注册成功" + data);
                        m.obj = "+++ register push sucess. token:" + data;
                        m.sendToTarget();
                    }

                    @Override
                    public void onFail(Object data, int errCode, String msg) {
                        Log.i(Constants.LogTag,
                                "+++ register push fail. token:" + data
                                        + ", errCode:" + errCode + ",msg:"
                                        + msg);

                        m.obj = "+++ register push fail. token:" + data
                                + ", errCode:" + errCode + ",msg:" + msg;
                        m.sendToTarget();
                    }
                });
        notificationService = NotificationService.getInstance(this);
        tabHost.setup();
        /** 监听 */
        TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {

                /** 碎片管理 */
                android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
                homeFragment = (Fav_Fragment) fm.findFragmentByTag("home");


                meFragment = (Setting_Fragment) fm.findFragmentByTag("me");
                index_Fragment = (Index_Fragment) fm.findFragmentByTag("index");
                ft = fm.beginTransaction();

                /** 如果存在Detaches掉 */
                if (homeFragment != null)
                    ft.detach(homeFragment);




                /** 如果存在Detaches掉 */
                if (meFragment != null)
                    ft.detach(meFragment);

                if (index_Fragment != null)
                    ft.detach(index_Fragment);

                // /** 如果当前选项卡是home */
                if (tabId.equalsIgnoreCase("home")) {
                    isTabHome();
                    CURRENT_TAB = 1;
                    // Intent intent = new Intent(MainActivity.this,
                    // MyMessageActivity.class);
                    // startActivity(intent);
                    /** 如果当前选项卡是wall */
                } else if (tabId.equalsIgnoreCase("wall")) {
                    isTabWall();
                    CURRENT_TAB = 2;
                }
                //
                // /** 如果当前选项卡是message */
                // }else
                else if (tabId.equalsIgnoreCase("index")) {
                    isTabIndex();
                    CURRENT_TAB = 5;
                } else if (tabId.equalsIgnoreCase("message")) {
                    isTabMessage();
                    CURRENT_TAB = 3;
                    // /** 如果当前选项卡是me */
                } else if (tabId.equalsIgnoreCase("me")) {
                    isTabMe();
                    CURRENT_TAB = 4;
                } else {
                    switch (CURRENT_TAB) {
                        case 1:
                            isTabHome();
                            // Intent intent = new Intent(MainActivity.this,
                            // MyMessageActivity.class);
                            // startActivity(intent);
                            break;
                        case 2:
                            isTabWall();
                            break;
                        case 3:
                            isTabMessage();
                            break;
                        case 4:
                            isTabMe();
                            break;
                        case 5:
                            isTabIndex();
                            break;
                    }

                }
                ft.commit();
            }

        };
        initTab();
        tabHost.setOnTabChangedListener(tabChangeListener);

        /** 设置初始化界面 */
        tabHost.setCurrentTab(1);

        boolean islianwang = new Constant().isConnect(MainActivity.this);
        if (!App.getInstance().isLogin()) {
            if (islianwang) {
                SendHttpData();
            } else {
                Toast.makeText(MainActivity.this, "请检查手机是否联网！", Toast.LENGTH_SHORT).show();
            }
        }

    }


    // 判断当前
    public void isTabHome() {

        if (homeFragment == null) {
            ft.add(R.id.realtabcontent, new Fav_Fragment(), "home");
        } else {
            ft.attach(homeFragment);
        }
        // Intent intent = new Intent(MainActivity.this,
        // MyMessageActivity.class);
        // startActivity(intent);
    }

    public void isTabWall() {


    }

    public void isTabMessage() {
//
//        if (messageFragment == null) {
//            ft.add(R.id.realtabcontent, new Uc_Fragment(), "message");
//        } else {
//            ft.attach(messageFragment);
//        }
    }

    public void isTabMe() {

        if (meFragment == null) {
            ft.add(R.id.realtabcontent, new Setting_Fragment(), "me");
        } else {
            ft.attach(meFragment);
        }
    }

    public void isTabIndex() {
        if (index_Fragment == null) {
            ft.add(R.id.realtabcontent, new Index_Fragment(), "index");
        } else {
            ft.attach(index_Fragment);
        }
    }

    /**
     * 设置通知自定义View，这样在下发通知时可以指定build_id。编号由开发者自己维护,build_id=0为默认设置
     *
     * @param context
     */
    @SuppressWarnings("unused")
    private void initCustomPushNotificationBuilder(Context context) {
        XGCustomPushNotificationBuilder build = new XGCustomPushNotificationBuilder();
        build.setSound(
                RingtoneManager.getActualDefaultRingtoneUri(
                        getApplicationContext(), RingtoneManager.TYPE_ALARM)) // 设置声音
                // setSound(
                // Uri.parse("android.resource://" + getPackageName()
                // + "/" + R.raw.wind)) 设定Raw下指定声音文件
                .setDefaults(Notification.DEFAULT_VIBRATE) // 振动
                .setFlags(Notification.FLAG_NO_CLEAR); // 是否可清除
        // 设置自定义通知layout,通知背景等可以在layout里设置
        build.setLayoutId(R.layout.notification);
        // 设置自定义通知内容id
        build.setLayoutTextId(R.id.content);
        // 设置自定义通知标题id
        build.setLayoutTitleId(R.id.title);
        // 设置自定义通知图片id
        build.setLayoutIconId(R.id.icon);
        // 设置自定义通知图片资源
        build.setLayoutIconDrawableId(R.drawable.logo);
//		// 设置状态栏的通知小图标
//		build.setIcon(R.drawable.right);
        // 设置时间id
        build.setLayoutTimeId(R.id.time);
        // 若不设定以上自定义layout，又想简单指定通知栏图片资源
        // build.setNotificationLargeIcon(R.drawable.ic_action_search);
        // 客户端保存build_id
        // XGPushManager.setPushNotificationBuilder(this, build_id, build);
    }

    /**
     * 找到Tabhost布局
     */
    public void findTabView() {
        // btnlooad =(Button)findViewById(R.id.btnloading);
        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabWidget = (TabWidget) findViewById(android.R.id.tabs);
        LinearLayout layout = (LinearLayout) tabHost.getChildAt(0);
        TabWidget tw = (TabWidget) layout.getChildAt(1);

        tabIndicator1 = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.tab_indicator, tw, false);
        ;
        ImageView ivTab1 = (ImageView) tabIndicator1.getChildAt(0);
        ivTab1.setBackgroundResource(R.drawable.selector_mood_home);

        tabIndicator3 = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.tab_indicator, tw, false);
        ImageView ivTab3 = (ImageView) tabIndicator3.getChildAt(0);
        ivTab3.setBackgroundResource(R.drawable.selector_mood_photograph);

        tabIndicator5 = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.tab_indicator, tw, false);
        ImageView ivTab5 = (ImageView) tabIndicator5.getChildAt(0);
        ivTab5.setBackgroundResource(R.drawable.selector_mood_my_wall);

    }

    /**
     * 初始化选项卡
     */
    public void initTab() {

        TabHost.TabSpec tSpecHome = tabHost.newTabSpec("home");
        tSpecHome.setIndicator(tabIndicator1);

        tSpecHome.setContent(new DummyTabContent(getBaseContext()));
        tabHost.addTab(tSpecHome);
        TabHost.TabSpec tSpecCamera = tabHost.newTabSpec("index");
        tSpecCamera.setIndicator(tabIndicator3);
        tSpecCamera.setContent(new DummyTabContent(getBaseContext()));
        tabHost.addTab(tSpecCamera);

        TabHost.TabSpec tSpecMe = tabHost.newTabSpec("me");
        tSpecMe.setIndicator(tabIndicator5);
        tSpecMe.setContent(new DummyTabContent(getBaseContext()));
        tabHost.addTab(tSpecMe);

    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int arg0) {
        // TODO Auto-generated method stub

    }

    @SuppressWarnings("static-access")
    public void SendHttpData() {
        String url = "http://120.237.110.50:8022/WebService.asmx/QueryVersion";
        RequestParams requestparams = new RequestParams(url, "POST");
        requestparams.put("PageIndex", "1");
        TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  String responseString) {
                // TODO Auto-generated method stub
                Log.e("TAG", "kkkabcresponseString---" + responseString);
                try {
                    if (responseString != null && !"".equals(responseString)) {
                        AnalysisVersionData(responseString);
                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                // TODO Auto-generated method stub

            }
        };
        try {
            restClient.post(url, requestparams, textHttpResponseHandler);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * json数据解析
     *
     * @param strResult
     * @throws JSONException
     */
    private void AnalysisVersionData(String strResult) throws JSONException {
        /**
         * 这里需要分析服务器回传的json格式数据，
         */
        String version = null;
        JSONObject jsonObject = new JSONObject(strResult);
        JSONArray jsonArray = jsonObject.getJSONArray("VersionInfoList");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
            contactData = new QueryVersion();
            contactData.setDeveloper(jsonObject2.getString("Developer"));
            contactData.setDescription(jsonObject2.getString("Description"));
            contactData.setProductName(jsonObject2.getString("ProductName"));
            contactData.setProductVersion(jsonObject2.getInt("ProductVersion"));
            contactData.setDownloadUrl(jsonObject2.getString("DownloadUrl"));
            Log.e("TAG", "kkkabcresponseString---解析完毕");
            // 显示版本号
            try {
                PackageInfo pkgInfo = MainActivity.this.getPackageManager()
                        .getPackageInfo(MainActivity.this.getPackageName(), 0);
                version = pkgInfo.versionName; // 得到版本信息
            } catch (Exception e) {
                e.printStackTrace();
            }
            newV = contactData.getProductVersion();
            currentV = (int) (Double.parseDouble(version) * 1000);
            if (newV > currentV) {
                Message msg = BroadcastHandler.obtainMessage();
                BroadcastHandler.sendMessage(msg);
            }

        }

    }

    private Handler BroadcastHandler = new Handler() {
        public void handleMessage(Message msg) {
            newVContent = "1.修改关于界面\n2.修改服务器配置\n3.修改更多服务bug";
            dialog = new Builder(MainActivity.this)
                    .setTitle("新版本更新内容")
                    .setMessage(newVContent)
                    .setPositiveButton("马上更新",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    Beginning();
                                    dialog.dismiss();
                                }
                            })
                    .setNegativeButton("以后再说",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int whichButton) {
                                    dialog.dismiss();
                                }
                            }).create();
            dialog.show();
        }
    };

    public void Beginning() {

    }

    public void loadFile(String url) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);

            HttpEntity entity = response.getEntity();
            float length = entity.getContentLength();

            InputStream is = entity.getContent();
            if (is != null) {
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 下载函数
                    filename = url.substring(url.lastIndexOf("/") + 1);
                    String pathfilename = Environment
                            .getExternalStorageDirectory() + "/" + filename;
                    FileOutputStream fileOutputStream = new FileOutputStream(
                            pathfilename);
                    byte[] buf = new byte[1024];
                    int ch = -1;
                    float count = 0;
                    while ((ch = is.read(buf)) != -1) {
                        fileOutputStream.write(buf, 0, ch);
                        count += ch;
                        sendMsg(1, (int) (count * 100 / length));
                    }
                    sendMsg(2, 0);
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } else {
                    Toast.makeText(MainActivity.this, "SD卡不存在", Toast.LENGTH_SHORT).show();
                }

            }

        } catch (Exception e) {
            sendMsg(-1, 0);
        }
    }

    private void sendMsg(int flag, int c) {
        Message msg = new Message();
        msg.what = flag;
        msg.arg1 = c;
        handler.sendMessage(msg);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case 1:
                        pb.setProgress(msg.arg1);
                        loading_process = msg.arg1;
                        tv.setText("已为您加载了：" + loading_process + "%");
                        break;
                    case 2:
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        dialog.dismiss();
                        intent.setDataAndType(Uri.fromFile(new File(Environment
                                        .getExternalStorageDirectory(), filename)),
                                "application/vnd.android.package-archive");
                        startActivity(intent);
                        break;
                    case -1:
                        String error = msg.getData().getString("error");
                        Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
            super.handleMessage(msg);
        }
    };

    public boolean isConnect(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(updateListViewReceiver);
        Log.e("sdfsd", "vvvvv---退出程序");
        // btnloading.setText("登录");
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private static class HandlerExtension extends Handler {
        WeakReference<MainActivity> mActivity;

        HandlerExtension(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity theActivity = mActivity.get();
            if (theActivity == null) {
                theActivity = new MainActivity();
            }
            if (msg != null) {
                Log.w(Constants.LogTag, msg.obj.toString());
            }
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        XGPushManager.onActivityStoped(this);
    }

}
